/*
 * @Author: zxc
 * @Date: 2020-11-29 13:42:13
 * @LastEditTime: 2020-11-29 18:42:54
 * @LastEditors: zxc
 * @Description:
 */
import * as Koa from "koa"
import { get, post, middlewares } from "../utils/decors"
import model from "../model/user"

const users = [
  {
    name: "tom"
  }
]

@middlewares([
  async function guard(ctx: Koa.Context, next: () => Promise<any>) {
    console.log("guard", ctx.header)

    if (ctx.header.token) {
      await next()
    } else {
      throw "请登录"
    }
  }
])
export default class User {
  @get("/users")
  public async list(ctx: Koa.Context) {
    // ctx.body = { ok: 1, data: users }
    const users = await model.findAll()
    ctx.body = { ok: 1, data: users }
  }
  @post("/users", {
    middlewares: [
      async function validation(ctx: Koa.Context, next: () => Promise<any>) {
        // 用户名，必须
        const name = ctx.request.body.name
        if (!name) {
          throw "请输入用户名"
        }
        await next()
        // 用户名不能重复
      }
    ]
  })
  public add(ctx: Koa.Context) {
    users.push(ctx.request.body)
    ctx.body = { ok: 1 }
  }
}
